package com.tencent.cloud.iov.processor.action;

import com.google.auto.service.AutoService;
import com.tencent.cloud.iov.action.Action;
import com.tencent.cloud.iov.processor.utils.LogHelper;

import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.ProcessingEnvironment;
import javax.annotation.processing.Processor;
import javax.annotation.processing.RoundEnvironment;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.TypeElement;

/**
 * 行为分发类创建处理器
 *
 * @author showxiao
 * @date 2018/4/18
 */

@AutoService(Processor.class)
public class ActionProcessor extends AbstractProcessor {

    private ActionMethodCollector mActionMethodCollector;
    private ActionDispatcherGenerator mActionDispatcherGenerator;
//    private ActionHandlerGenerator mActionHandlerGenerator;
    private LogHelper mLogHelper;

    @Override
    public synchronized void init(ProcessingEnvironment processingEnv) {
        super.init(processingEnv);
        mActionMethodCollector = new ActionMethodCollector(processingEnv);
        mActionDispatcherGenerator = new ActionDispatcherGenerator(processingEnv);
//        mActionHandlerGenerator = new ActionHandlerGenerator(processingEnv);
        mLogHelper = new LogHelper(processingEnv);
    }

    @Override
    public boolean process(Set<? extends TypeElement> set, RoundEnvironment roundEnv) {
        try {
            final Map<TypeElement, List<ExecutableElement>> actionMethods =
                    mActionMethodCollector.collect(roundEnv);
            if (actionMethods == null || actionMethods.isEmpty()) {
                return true;
            }

            final Set<TypeElement> classElements = actionMethods.keySet();
            for (TypeElement classElement : classElements) {
                mActionDispatcherGenerator.generate(classElement, actionMethods.get(classElement));
            }

//            mActionHandlerGenerator.generate(classElements);

        } catch (Exception e) {
            mLogHelper.error(null, e.toString());
        }

        return true;
    }

    @Override
    public Set<String> getSupportedAnnotationTypes() {
        Set<String> set = new HashSet<>(1);
        set.add(Action.class.getCanonicalName());
        return set;
    }

    @Override
    public SourceVersion getSupportedSourceVersion() {
        return SourceVersion.latestSupported();
    }
}
